using UnityEditor;
using UnityEngine;

//ref: https://blog.csdn.net/njiyue/article/details/141221274
[InitializeOnLoad]
public class DragToHierarchy
{
    static DragToHierarchy()
    {
        DragAndDrop.AddDropHandler(HierarchyDropHandler);
    }

    private static DragAndDropVisualMode HierarchyDropHandler(int dropTargetInstanceID, HierarchyDropFlags dropMode, Transform parentForDraggedObjects, bool perform)
    {
        var obj = EditorUtility.InstanceIDToObject(dropTargetInstanceID);//拖拽放置目标对象
        if (!perform)//在拖拽中时
        {
            //仅支持拖拽1个脚本文件
            if (DragAndDrop.objectReferences.Length == 1 && DragAndDrop.objectReferences[0] is MonoScript)
            {
                if (obj == null)
                    return DragAndDropVisualMode.Generic;//放置目标为空时，改变VisualMode
            }
        }
        else//在拖拽放下时
        {
            if (DragAndDrop.objectReferences.Length == 1 && DragAndDrop.objectReferences[0] is MonoScript script && obj == null)
            {
                if (typeof(Component).IsAssignableFrom(script.GetClass()))//判定脚本文件的类型是否为组件
                    Selection.activeObject = new GameObject(script.GetClass().Name, script.GetClass());//创建新物体，并加组件
                else
                    Debug.Log($"非组件脚本文件：{script.name}");
            }
        }
        return DragAndDropVisualMode.None;
    }
}
